package hufs.twotwoco.manager;

import hufs.twotwoco.object.ManageObject;
import hufs.twotwoco.object.UserObject;
import hufs.twotwoco.pmf.PMF;
import hufs.twotwoco.utils.Debugger;
import hufs.twotwoco.var.Var;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.SendResponse;
import com.google.appengine.api.xmpp.Subscription;
import com.google.appengine.api.xmpp.SubscriptionType;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;
import com.google.appengine.labs.repackaged.org.json.JSONArray;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;

public class ManagerServlet<XMPPServicexmppService> extends HttpServlet {

	Debugger dbg = new Debugger();
	JSONObject jo;
	PrintWriter out;
	String uid;
	String nfc;
	String name;
	String size;
	String milk;
	String shot;
	String whipping;
	String receive;
	Long key;
	int num;

	int op;

	XMPPService xmppService = XMPPServiceFactory.getXMPPService();

	/*
	 * public void doPost(HttpServletRequest req, HttpServletResponse resp)
	 * throws IOException {
	 * 
	 * System.out.println("hiohihihihihihihi"); }
	 */
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		dbg.debug("doGet start in ManagerServlet");
		try {
			nfc = req.getParameter(Var.KEY_NFC);
			uid = req.getParameter(Var.KEY_UID);
			name = req.getParameter(Var.KEY_NAME);
			op = Integer.parseInt(req.getParameter(Var.KEY_OPERATION));
			num = Integer.parseInt(req.getParameter(Var.KEY_NUM));
			size = req.getParameter(Var.KEY_SIZE);
			whipping = req.getParameter(Var.KEY_WHIPPING);
			shot = req.getParameter(Var.KEY_SHOT);
			milk = req.getParameter(Var.KEY_MILK);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		PrintWriter out = resp.getWriter();

		try {

			if (op == Var.OP_Tagging_NFC) {
				nfctagging(req, resp);
			} else if (op == Var.OP_VIEW_SELECTED_Coffe) {
				viewSelectedCoffes(req, resp);
			}
			/*
			 * Welse if (op == Var.OP_VIEW_MY_SHOPPING) { shoppingBasket(req,
			 * resp); } else if(op == Var.OP_SEARCH_PWD){ SerachPwd(req,resp); }
			 */
		} finally {
			out.close();
		}

		dbg.debug("doGet end in ManagerServlet");

	}

	private void sendMsg(String id, String body) {

		JID jid = new JID(id + "@gmail.com");

		Message msg = new MessageBuilder().withRecipientJids(jid)
				.withBody(body).build();
		boolean messageSent = false;

		XMPPService xmpp = XMPPServiceFactory.getXMPPService();
		if (xmpp.getPresence(jid).isAvailable()) {
			SendResponse status = xmpp.sendMessage(msg);

			messageSent = (status.getStatusMap().get(jid) == SendResponse.Status.SUCCESS);
		}
		if (!messageSent) {

		}
	}

	private void nfctagging(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		dbg.debug("nfc tag start");
		PersistenceManager ipm = PMF.get().getPersistenceManager();
		PersistenceManager upm = PMF.get().getPersistenceManager();
		out = resp.getWriter();
		String query = "SELECT FROM " + UserObject.class.getName()
				+ " WHERE nfc == " + "'" + nfc + "'";
		List<UserObject> TagNfc = (List<UserObject>) ipm.newQuery(query)
				.execute();
		try {
			dbg.debug("TagNfc size is " + TagNfc.size());
			dbg.debug("TagNfc size is " + milk);
			if (TagNfc.size() > 0) {
				UserObject sc = TagNfc.get(0);
				String uid = sc.getUid();
				long key = sc.getKey();
				String table = sc.getTable();
				String body = table;
				sendMsg(uid, body);
				UserObject u = new UserObject(key,nfc,uid,table);
				upm.makePersistent(u);
			} else {
				setUser();
			}
		} finally {
			ipm.close();
			dbg.debug("nfc tag end");
			out.close();
		}

	}

	private void setUser() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String query = "SELECT FROM " + UserObject.class.getName()
				+ " WHERE nfc == '0'";
		List<UserObject> TagNfcFrist = (List<UserObject>) pm.newQuery(query)
				.execute();
		try {
			dbg.debug("TagNfc size is " + TagNfcFrist.size());
			UserObject sc = TagNfcFrist.get(0);
			String uid = sc.getUid();
			Long key = sc.getKey();
			String table = sc.getTable();
			UserObject no = new UserObject(key, nfc, uid, table);
			pm.makePersistent(no);
		} finally {
			pm.close();
		}
	}

	/*
	 * private void SerachPwd(HttpServletRequest req, HttpServletResponse resp)
	 * throws IOException { PersistenceManager pm =
	 * PMF.get().getPersistenceManager(); String query = "SELECT FROM " +
	 * UserObject.class.getName() + " WHERE uid = " + "'" + uid + "'";
	 * List<UserObject> SearchPwd = (List<UserObject>) pm.newQuery(query)
	 * .execute(); try { JSONObject jo = new JSONObject(); UserObject sp =
	 * SearchPwd.get(0); jo.put(Var.KEY_PWD, sp.getPwd());
	 * out.print(jo.toString()); }catch (JSONException e) { // TODO
	 * Auto-generated catch block e.printStackTrace(); } finally { pm.close(); }
	 * }
	 */

	private void viewSelectedCoffes(HttpServletRequest req,
			HttpServletResponse resp) throws IOException {

		dbg.debug("viewSelectedCoffes start in ManagerServlet");
		PersistenceManager pm = PMF.get().getPersistenceManager();
		out = resp.getWriter();
		String query1 = "SELECT FROM " + UserObject.class.getName()
				+ " WHERE uid == " + "'" + uid + "'";
		List<UserObject> Table = (List<UserObject>) pm.newQuery(query1)
				.execute();
		try {	
			UserObject s = Table.get(0);
			String table = s.getTable();
			ManageObject iob = new ManageObject(uid, name, size, milk, shot,
					whipping, num, table);
			pm.makePersistent(iob);

		} finally {
			dbg.debug("select coffe end");
			out.close();
			pm.close();
		}

	}

	/*
	 * private void shoppingBasket(HttpServletRequest req, HttpServletResponse
	 * resp) throws IOException {
	 * dbg.debug("shoppingBasket start in ManagerServlet");
	 * 
	 * out = resp.getWriter();
	 * 
	 * JSONArray shop = new JSONArray();
	 * 
	 * JSONObject result = new JSONObject();
	 * 
	 * try {
	 * 
	 * PersistenceManager mpm = PMF.get().getPersistenceManager();
	 * 
	 * String mQuery = "SELECT FROM " + ManageObject.class.getName() +
	 * " WHERE uid == " + "'" + uid + "'"; dbg.debug(mQuery);
	 * 
	 * List<ManageObject> myShoppinglist = (List<ManageObject>) mpm
	 * .newQuery(mQuery).execute();
	 * 
	 * for (int i = 0; i < myShoppinglist.size(); i++) {
	 * 
	 * ManageObject sh = myShoppinglist.get(i); JSONObject shjo = new
	 * JSONObject(); shjo.put(Var.KEY_NAME, sh.getName()); shjo.put(Var.KEY_NUM,
	 * sh.getNum()); shjo.put(Var.KEY_MILK, sh.getMilk());
	 * shjo.put(Var.KEY_SHOT, sh.getShot()); shjo.put(Var.KEY_SIZE,
	 * sh.getSize()); shjo.put(Var.KEY_WHIPPING, sh.getWhipping());
	 * shop.put(shjo);
	 * 
	 * }
	 * 
	 * mpm.close();
	 * 
	 * result.put("myShopCoffe", shop);
	 * 
	 * out.print(result.toString()); } catch (JSONException e) { // TODO
	 * Auto-generated catch block e.printStackTrace(); } finally { out.close();
	 * }
	 * 
	 * dbg.debug(" shoppingBasket end in BookManagerServlet");
	 * 
	 * }
	 */
	private String getPureUid(String uid) {
		return uid.substring(0, uid.indexOf("/"));

	}

	public boolean inspectLogin(HttpServletRequest req, HttpServletResponse resp) {

		dbg.debug("start inspect Customer");

		PersistenceManager pm = PMF.get().getPersistenceManager();

		String query = "SELECT FROM " + UserObject.class.getName()
				+ " WHERE uid == " + "'" + uid + "'";

		List<UserObject> user = (List<UserObject>) pm.newQuery(query).execute();
		try {
			if (user.size() > 0) {
				return true;
			} else {
				return false;
			}
		} finally {
			dbg.debug("end inspect Customer");
			pm.close();
		}

	}

}
